package com.ln.prac.base.xiaoao.collections;

import java.util.Iterator;
import java.util.LinkedHashMap;

/**
 * 基于{@link Iterable}实现的LRUCache，只做演示
 *
 * @Author zhangj
 * @Date 2023/1/27 22:13
 */
public class LRUCache<K, V> implements Iterable<K> {

    private int maxSize = 10;

    private final LinkedHashMap<K, V> linkedHashMap = new LinkedHashMap();


    public void cache(K key, V value) {
        if(linkedHashMap.containsKey(key)) {
            linkedHashMap.remove(key);
        } else if(linkedHashMap.size() >= maxSize) {
            // 删除第一个元素
            linkedHashMap.remove(linkedHashMap.entrySet().iterator().next());
        }
        linkedHashMap.put(key, value);
    }

    @Override
    public Iterator<K> iterator() {
        return linkedHashMap.keySet().iterator();
    }
}
